# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_xmlrpc_upload_client.py 
@time: 2019/7/24 上午9:39
@note:
基于xmlrpc的文件上传下载文件显示查询-客户端
"""
from xmlrpc.client import ServerProxy, SafeTransport
from xmlrpc.client import Binary
import os
import ssl

# 验证证书
class VerifyCertSslClient(SafeTransport):
    def __init__(self, cafile, certfile=None, keyfile=None):
        SafeTransport.__init__(self)
        self._cafile = cafile
        self._certfile = certfile
        self._keyfile = keyfile

    def get_ssl_context(self):

        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.load_verify_locations(self._cafile)
        if self._certfile:
            context.load_cert_chain(certfile=self._certfile, keyfile=self._keyfile)
        context.verify_mode = ssl.CERT_REQUIRED

        return context
# 连接服务
KEYFILE='client_key.pem'
CERTFILE='client_cert.pem'
CA_CERTS='server_cert.pem'

ssl_con=VerifyCertSslClient(keyfile=KEYFILE, certfile=CERTFILE, cafile=CA_CERTS)
serv = ServerProxy('https://10.120.21.180:18000',context=ssl_con.get_ssl_context(), allow_none=True)

'上传文件'
fname = '/home/autumner/下载/refer-master.zip'
_, filename = os.path.split(fname)
with open(fname, 'rb') as f:
    result = Binary(f.read())
    if serv.upload(result, fname): print(f'{filename},上传完成!')
print('显示所有文件')
for li in serv.show(): print(f"{li[0]} {li[1]} {li[2]}")
print('查找“明细表”文件')
for li in serv.query('明细表'): print(f"{li[0]} {li[1]} {li[2]}")
'下载文件'
fpath = '/home/autumner'
fname = 'refer-master.zip'
if serv.down(fname):
    with open(os.path.join(fpath, fname), 'wb') as f:
        f.write(serv.down(fname).data)
    print(f"{fname},下载完成")
else:
    print(f"{fname} no found!")
